<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * @author Truong Kim Phung
 * @copyright 2014
 */
 class CI_Function {
    /**
    * @author: Truong Kim Phung
    * @date: January 22, 2014
    * @description: redirect to url
    * @param 
    *   strUrl
    * @return
    */
    public static function redirect($strUrl) {
        header('location: ' . $strUrl);
    }
    /**
    * @author: Truong Kim Phung
    * @date: January 22, 2014
    * @description: get current date system   
    * @return date
    */
    public static function now() {
        return date('Y-m-d H:i:s');
    }
    /**
    * @author: Truong Kim Phung
    * @date: January 22, 2014
    * @description: ip client   
    * @return date
    */
    public static function getIp() {
		return (getenv('HTTP_X_FORWARDED_FOR')) ?  getenv('HTTP_X_FORWARDED_FOR') :  getenv('REMOTE_ADDR');
	}
    /**
    * @author: Truong Kim Phung
    * @date: January 22, 2014
    * @description: base64 Encode   
    * @return date
    */
    public static function base64E($str)
	{
		return str_replace('/', SITE_PREFIX, base64_encode($str));
	}
    /**
    * @author: Truong Kim Phung
    * @date: January 22, 2014
    * @description: base64 Decode  
    * @return date
    */
	public static function base64D($str,$option=0)
	{
		if($option == 0) {
			return base64_decode(str_replace(SITE_PREFIX, '/', $str));
		} else {
			return base64_decode($str);
		}
	}
    /**
    * @author: Truong Kim Phung
    * @date: January 22, 2014
    * @description: The hexadecimal string to convert 
    * @param
    *   $strHex: hex string   
    * @return int
    */
    public static function hex2Dec($strHex)
	{
	    if ($strHex != '' && $strHex > 0) {
			$intIdDecode = hexdec($strHex)-900000000;
			return $intIdDecode;
		}
		return 0;
	}
    /**
    * @author: Truong Kim Phung
    * @date: January 22, 2014
    * @description: The decimal value to convert. 
    * @param
    *   $intDec: number   
    * @return string 
    */
	public static function dec2Hex($intDec)
	{
	    $strIdEncode = dechex(900000000 + $intDec);
		return strtoupper($strIdEncode);
	}
    public static function setMsg($strMsg)
	{
		$_SESSION[SESSION_MESSAGE] = CI_Function::base64E($strMsg);
	}
	public static function getMsg()
	{		
		$strMsg = '';
		if (isset($_SESSION[SESSION_MESSAGE])) {
			$strMsg = CI_Function::base64D($_SESSION[SESSION_MESSAGE]);
			unset($_SESSION[SESSION_MESSAGE]);
		}
		return $strMsg;
	}
	public static function setError($strMsg)
	{
		$_SESSION[SESSION_ERROR] = CI_Function::base64E($strMsg);
	}
	public static function getError()
	{
		$strMsg = '';
		if (isset($_SESSION[SESSION_ERROR])) {
			$strMsg = CI_Function::base64D($_SESSION[SESSION_ERROR]);
			unset($_SESSION[SESSION_ERROR]);
		}
		return $strMsg;
	}
    /**
    * @author: Truong Kim Phung
    * @date: January 22, 2014
    * @description: create hash code    
    * @return string 
    */
	public static function hash() {
		return md5(uniqid(rand(),1));
	}
    /**
    * @author: Truong Kim Phung
    * @date: January 22, 2014
    * @description: create directory and chmod 777
    * @param
    *   $strTarget: string folder path   
    * @return string 
    */
    public static function mkDirectory($strTarget) {
		// from php.net/mkdir user contributed notes
		if (file_exists ( $strTarget )) {
			if (! @ is_dir ( $strTarget ))
				return false;
			else
				return true;
		}
		
		// Attempting to create the directory may clutter up our display.
		if (@ mkdir ( $strTarget )) {
			$stat = @ stat ( dirname ( $strTarget ) );
			$dir_perms = $stat ['mode'] & 0007777; // Get the permission bits.
			@ chmod ( $strTarget, $dir_perms );
			return true;
		} else {
			if (is_dir ( dirname ( $strTarget ) ))
				return false;
		}
		
		// If the above failed, attempt to create the parent node, then try again.
		if (CI_Function::mkDirectory ( dirname ( $strTarget ) ))
			return mkDir ( $strTarget );
		
		return false;
	}
    /**
    * @author: Truong Kim Phung
    * @date: January 22, 2014
    * @description: get url current
    * @param
    *   $intParams  
    * @return string 
    */
    public static function urlPaging($intParams = 0, $strName='page')
	{
		$strUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
		if ($intParams == 0) {
			$intChr	= '?';
			$intPos	= strpos($strUrl, '?'.$strName.'=');
		} else {
			$intChr	= '&';
			$intPos	= strpos($strUrl, '&'.$strName.'=');
		}
		if ($intPos != false) {
			$strUrl = substr($strUrl, 0, $intPos);
		}
		return $strUrl . $intChr;
	}
    /**
    * @author: Truong Kim Phung
    * @date: January 27, 2014
    * @description: strip tag data before insert/update database
    * @param string $str
    * @param string $act: name, short, tag, comment, .... Default act=name
    * @return string
    */
    public static function stripTag($str, $act='name') {  
        // empty string || undefined
        if(empty($str) || !isset($str)) return null;
        // decode url string
        $str	       = urldecode($str);
        // html entity decode string
        $str	       = html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
        //clear space left and right string
        $str           = trim($str);
        $strAllowTag   = '';
        if(isset($act)) {
            switch($act) {
                case 'name':
                case 'title':
                case 'code':
                case 'short':
                case 'tag': // name, title, short, tag ...
                    break;
                case 'comment': // comment
                    $strAllowTag    = '<a>,<img>,<br/>,' . "\n";
                    break;
                case 'fckadmin': // admin create
                    $strAllowTag    = '<p>,<font>,<span>,<a>,<img>,<h1>,<h2>,<h3>,<h4>,<h5>,<h6>,<strong>,<b>,<em>,<i>,<u>,<br/>,' . "\n" . ',<sub>,<sub>,<video>,<iframe>,<object>,<param>,<embed>,<ul>,<ol>,<li>,<table>,<tbody>,<thead>,<tfoot>,<tr>,<th>,<td>';
                    break;
            }
        }
        return strip_tags($str, $strAllowTag);
    }
    /**
     * @author: Truong Kim Phung
     * @date: January 27, 2014
     * @description: cut string
     * @param string $str
     * @param int $maxlength: number characters length after cut string. Default 250
     * @param string suffix: default "..." characters
     * @return string
     * 
    */
    public static function wordCut($str, $maxlength=VL_SHORT_MAXLENGTH, $suffix='...') {
        // empty string || undefined
        if(empty($str) || !isset($str)) return null;
        // strip tag data input
        $str = CI_Function::stripTag($str, 'short');
        // length string
        $len = strlen($str);
        // compare 
        if($len > $maxlength) {
            $lenSuffix      = strlen($suffix);
            $strWordwrap 	= wordwrap($str, ($maxlength-$lenSuffix), '[cut]', 1);
			$arrCut 	    = explode('[cut]', $strWordwrap);      
			$strCut 	    = $arrCut[0];      
			$strReturn 	    = $strCut;
            $lenReturn      = strlen($strReturn);            
            if($lenReturn < ($maxlength-$lenSuffix)) {
                $strReturn = $strCut . $suffix;
            }
        } else {
            $strReturn  = $str . $suffix;
        }
        return trim($strReturn);
    }
    /**
     * @author: Truong Kim Phung
     * @date: February 9, 2014
     * @description: validate code. Ex: section, admin ...
     * @param string $strCode
     * @return boolean
     * 
    */
    public static function isValidCode($strCode) {		
		if(preg_match('/^([a-zA-Z]{2,20})+([a-zA-Z_]{1,20})$/', $strCode)) {			
			return true;
		}
		return false;
	}
    /**
     * @author: Truong Kim Phung
     * @date: February 9, 2014
     * @description: convert array to integer
     * @param array $arr
     * @return integer
     * 
    */
    public static function convertArrToInt($arr) {
		if(is_array($arr)) {
			$int = '';
			$length = count($arr);
			for($i=0;$i<$length;$i++) {
				$int += $arr[$i];				
			}
			return $int;
		}
		return -1;
	}
     /**
     * @author: Truong Kim Phung
     * @date: February 14, 2014
     * @description: convert string to datetime
     * @param string $strDate
     * @return string format date system
     * 
    */
    public static function convertStrToDate($strDate) {
		if($strDate == '') return '';
		$arrExplode = explode('/', $strDate);		
		if(count($arrExplode) > 1) {
			return $arrExplode[2] . '-' . $arrExplode[1] . '-' . $arrExplode[0];
		}
		return '';
	}
     /**
     * @author: Nguyen Thanh Tung
     * @date: February 14, 2014
     * @description: isEmail 
     * @param string $strEmail
     * @return string
     * 
    */
	public static function isEmail($email){
		$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/';
		if (preg_match($regex, $email)) {
			return true;
		} else { 
			 return false;
		}
	}
	/**
     * @author: Nguyen Thanh Tung
     * @date: February 14, 2014
     * @description: isUsername
     * @param string $username
     * @return boll
     * 
    */
	function isUsername($username){
		$regex = '/^[a-zA-Z](([\._\-][a-zA-Z0-9])|[a-zA-Z0-9])*[a-z0-9]$/';
		if (preg_match($regex, $username)) {
			return true;
		} else { 
			 return false;
		}
	}
	 /**
	*	@author: Nguyen Thanh Tung
	*	@date: 13/2/2014
	*	@description: format date date/month/year
	*	@param: string $day.	
	*	@return: string
	*/
	public static function datevn($day='', $dot='/'){
		if(empty($day)) return '';
		return strftime("%d$dot%m$dot%Y", strtotime($day));
	} 
	 /**
	*	@author: Nguyen Thanh Tung
	*	@date: 13/2/2014
	*	@description: get Year
	*	@param: string $day.	
	*	@return: string
	*/
	public static function getYears($day=''){
		if(empty($day)) return '';
		return date("Y", strtotime($day)); 
	} 
    public static function exportJs($lang, &$arrOk=null) {
        $path    = LOCALE_DIR . $lang;
        $langDir = LANGUAGE_DIR . $lang; 
        if(!file_exists($langDir)) {
            return 'FOLDER ' . $langDir . ' NOT EXISTS';
        }
        if (!file_exists($path) ) { 
            CI_Function::mkDirectory($path);
        }
        // scan file in folder    
        $files   = scandir($langDir);        
        if(isset($files) && is_array($files)) {
            
            foreach ($files as $file ) {                    
                if( $file !== '.' && $file !== '..' && $file !== 'index.html') {                
                    $fileDir = $langDir . '/'. $file;                               
                    if( file_exists($fileDir) ) {                    
                        $js      = rtrim($path . '/' . $file, '.php') . '.js';
                        if(file_exists($js)) @unlink($js);
                        include($fileDir);
                        if(isset($arrLocale)) {
                            $strContent = '';
                            foreach ($arrLocale as $k=>$v ) {
                                if((int)$v > 0) {
            						$strContent .= 'var ' . $k . '=' . $v . ";\n";
            					} else {
            						$strContent .= 'var ' . $k . '="' . $v . "\";\n";
            					}
                            }                                      
                            file_put_contents($js,$strContent);
                            $arrOk[$lang][] = $js;
                            $arrLocale = null; 
                        }
                                           
                    }
                }
            } 
        }
    }
    /**
	*	@author: Pham Van Diep
	*	@date: 13/2/2014
	*	@description: lay url tu duong dan tuong doi
	*	@param: string duong dan tuong doi cua image	
	*	@return: string
	*/
	public static function getUrl($image_path) {
		return isset($image_path) ? HOST_UPLOAD .'club'. '/' .$image_path : '';
	}
    /**
	*	@author: Pham Van Diep
	*	@date: 13/2/2014
	*	@description: lay url tu duong dan tuong doi
	*	@param: string duong dan tuong doi cua image	
	*	@return: string
	*/
	public static function getImageUrl($path,$name, $width, $height,$ext) {
		return HOST_UPLOAD .'club'. '/' .$path.$name.'.'.$width.'x'.$height.'.'.ltrim($ext,'.');
	}
    /**
	*	@author: Pham Van Diep
	*	@date: 12/2/2014
	*	@description: xoa tat ca nhung file lien quan	
	*	@param: string duong dan thu muc chua hinh	
	*	@param: string ten cua hinh khong co phan kich thuoc phia sau	
	*	@return: hinh duoc resize
	*/
	public static function deleteRelativeImage($strDir , $strName) {
		// khong phai thu muc
		if( ! is_dir(IMAGE_UPLOAD_DIR.$strDir) || strlen($strName) <= 0) return 0;	
		$files = scandir(IMAGE_UPLOAD_DIR.$strDir);
		$pattern = '/'.strtolower($strName).'/i';
		foreach ($files as $file) {			
			if( preg_match($pattern , $file ) == 1 && is_file($strDir. DIRECTORY_SEPARATOR .$file) ) {					
				unlink(IMAGE_UPLOAD_DIR.$strDir. DIRECTORY_SEPARATOR .$file);
			}			
			return 1;
		}
	}
	/**
	*	@author: Pham Van Diep
	*	@date: 23/2/2014
	*	@description: Loai bo dau tieng viet
	*	@params: string $str
	*	@return: string
	*/
    public static function UTF8Deaccent($str)
	{
		$str	= html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
    	$trans = array
    	(
			// C1 Controls and Latin-1 Supplement (0080 - 00FF)
			'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'È' => 'E',
			'É' => 'E', 'Ê' => 'E', 'Ì' => 'I', 'Í' => 'I',
			'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O',
			'Ù' => 'U', 'Ú' => 'U', 'à' => 'a', 'á' => 'a',
			'â' => 'a', 'ã' => 'a', 'è' => 'e', 'é' => 'e',
			'ê' => 'e', 'ì' => 'i', 'í' => 'i', 'ò' => 'o',
			'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ù' => 'u',
			'ú' => 'u', 'ý' => 'y',
			// Latin Extended-A (0100 - 017F)
			'Ă' => 'A', 'ă' => 'a', 'Đ' => 'D', 'đ' => 'd',
			'Ĩ' => 'I', 'ĩ' => 'i',	'Ũ' => 'U', 'ũ' => 'u',
			// Latin Extended-B (0180 - 024F)
			'Ơ' => 'O', 'ơ' => 'o',	'Ư' => 'U', 'ư' => 'u',
			// Latin Extended Additional (1E80 - 1EFF)
			'Ạ' => 'A', 'ạ' => 'a',	'Ả' => 'A', 'ả' => 'a',
			'Ấ' => 'A', 'ấ' => 'a',	'Ầ' => 'A', 'ầ' => 'a',
			'Ẩ' => 'A', 'ẩ' => 'a',	'Ẫ' => 'A', 'ẫ' => 'a',
			'Ậ' => 'A', 'ậ' => 'a', 'Ắ' => 'A', 'ắ' => 'a',
			'Ằ' => 'A', 'ằ' => 'a', 'Ẳ' => 'A', 'ẳ' => 'a',
			'Ẵ' => 'A', 'ẵ' => 'a', 'Ặ' => 'A', 'ặ' => 'a',
			'Ẹ' => 'E', 'ẹ' => 'e', 'Ẻ' => 'E', 'ẻ' => 'e',
			'Ẽ' => 'E', 'ẽ' => 'e', 'Ế' => 'E', 'ế' => 'e',
			'Ề' => 'E', 'ề' => 'e', 'Ể' => 'E', 'ể' => 'e',
			'Ễ' => 'E', 'ễ' => 'e', 'Ệ' => 'E', 'ệ' => 'e',
			'Ỉ' => 'I', 'ỉ' => 'i', 'Ị' => 'I', 'ị' => 'i',
			'Ọ' => 'O', 'ọ' => 'o', 'Ỏ' => 'O', 'ỏ' => 'o',
			'Ố' => 'O', 'ố' => 'o', 'Ồ' => 'O', 'ồ' => 'o',
			'Ổ' => 'O', 'ổ' => 'o', 'Ỗ' => 'O', 'ỗ' => 'o',
			'Ộ' => 'O', 'ộ' => 'o', 'Ớ' => 'O', 'ớ' => 'o',
			'Ờ' => 'O', 'ờ' => 'o', 'Ở' => 'O', 'ở' => 'o',
			'Ỡ' => 'O', 'ỡ' => 'o', 'Ợ' => 'O', 'ợ' => 'o',
			'Ụ' => 'U', 'ụ' => 'u', 'Ủ' => 'U', 'ủ' => 'u',
			'Ứ' => 'U', 'ứ' => 'u', 'Ừ' => 'U', 'ừ' => 'u',
			'Ử' => 'U', 'ử' => 'u', 'Ữ' => 'U', 'ữ' => 'u',
			'Ự' => 'U', 'ự' => 'u', 'Ỳ' => 'Y', 'ỳ' => 'y',
			'Ỵ' => 'Y', 'ỵ' => 'y',	'Ỷ' => 'Y', 'ỷ' => 'y',
			'Ỹ' => 'Y', 'ỹ' => 'y'
		);
		return trim(strtr($str, $trans));
	}
	/**
	*	@author: Pham Van Diep
	*	@date: 23/2/2014
	*	@description: Loai bo nhung ki tu dac biet trong chuoi
	*	@params: string $str
	*	@return: string
	*/
    public static function urlFriendly($string, $length = 255, $strSymbol='-', $isToLower = 1)
	{
		$arrCharFrom= array(
							   "ạ","á","à","ả","ã","Ạ","Á","À","Ả","Ã",
							   "â","ậ","ấ","ầ","ẩ","ẫ","Â","Ậ","Ấ","Ầ","Ẩ","Ẫ",
							   "ă","ặ","ắ","ằ","ẳ","ẫ","Ă","Ắ","Ằ","Ẳ","Ẵ","Ặ",
							   "ê","ẹ","é","è","ẻ","ẽ","Ê","Ẹ","É","È","Ẻ","Ẽ",
							   "ế","ề","ể","ễ","ệ","Ế","Ề","Ể","Ễ","Ệ",
							   "ọ","ộ","ổ","ỗ","ố","ồ","Ọ","Ộ","Ổ","Ỗ","Ố","Ồ","Ô","ô",
							   "ó","ò","ỏ","õ","Ó","Ò","Ỏ","Õ",
							   "ơ","ợ","ớ","ờ","ở","ỡ",
							   "Ơ","Ợ","Ớ","Ờ","Ở","Ỡ",
							   "ụ","ư","ứ","ừ","ử","ữ","ự","Ụ","Ư","Ứ","Ừ","Ử","Ữ","Ự",
							   "ú","ù","ủ","ũ","Ú","Ù","Ủ","Ũ",
							   "ị","í","ì","ỉ","ĩ","Ị","Í","Ì","Ỉ","Ĩ",
							   "ỵ","ý","ỳ","ỷ","ỹ","Ỵ","Ý","Ỳ","Ỷ","Ỹ",
							   "đ","Đ"
				   		);
	   $arrCharEndNoVn= array(
							   "a","a","a","a","a","A","A","A","A","A",
							   "a","a","a","a","a","a","A","A","A","A","A","A",
							   "a","a","a","a","a","a","A","A","A","A","A","A",
							   "e","e","e","e","e","e","E","E","E","E","E","E",
							   "e","e","e","e","e","E","E","E","E","E",
							   "o","o","o","o","o","o","O","O","O","O","O","O","O","o",
							   "o","o","o","o","O","O","O","O",
							   "o","o","o","o","o","o",
							   "O","O","O","O","O","O",
							   "u","u","u","u","u","u","u","U","U","U","U","U","U","U",
							   "u","u","u","u","U","U","U","U",
							   "i","i","i","i","i","I","I","I","I","I",
							   "y","y","y","y","y","Y","Y","Y","Y","Y",
							   "d","D"
	   						);
		$arrCharFilter = str_replace($arrCharFrom,$arrCharEndNoVn,trim($string));
		if($strSymbol != '')		{
			if (mb_strlen($arrCharFilter,"UTF-8") > $length) {
				$arrCharFilter = mb_substr($arrCharFilter, 0, $length,"UTF-8");
			}		
			$arrCharFilter = preg_replace('/[\W|_]+/',$strSymbol,$arrCharFilter);
		}
		return $isToLower ? trim(strtolower($arrCharFilter)) : trim($arrCharFilter);
	}
	/**
	*	@author: Pham Van Diep
	*	@date: 23/2/2014
	*	@description: Thay space bang ki tu khac
	*	@params: string $str
	*	@return: string
	*/
    public static function replaceSpace($str,$char='-') {
		if(!$str) return false;
        else return preg_replace('/[[:space]]/',$char,$str); 
	}
	/**
	*	@author: Pham Van Diep
	*	@date: 23/2/2014
	*	@description: tao duong link tu 1 chuoi
	*	@params: string $str
	*	@return: string
	*/
    public static function makeLink($str) {
		if(!$str) {
			return false;
		}
        else{
			return self::replaceSpace(self::removeSpecialChar(self::filterVietnamese(trim($str))));
		}
	}
	/**
	*	@author: Pham Van Diep
	*	@date: 12/2/2014
	*	@description: resize hinh	
	*	@param: string duong dan cua hinh	
	*	@param: int chieu rong hinh can resize
	*	@param: int chieu cao hinh can resize
	*	@return: hinh duoc resize
	*/
	public static function resize($image_path, $width = IMAGE_THUMBNAIL_WIDTH, $height = IMAGE_THUMBNAIL_HEIGHT,  $image_thumb=null) {	
		
		include_once('Thumbnail.php');
		$thumb = new CI_Thumbnail(realpath(IMAGE_UPLOAD_DIR  .$image_path));			
		if($width > $height && $width > 0) {
			$thumb->size_width($height);
		} elseif($width < $height && $height > 0) {
			$thumb->size_height($height);
		}
		$thumb->process();
		if(!isset($image_thumb)) {
			$arrPath = explode('.',realpath(IMAGE_UPLOAD_DIR  .$image_path));			
			$new_path = $arrPath[0]. '.' . $width . 'x' . $height . '.' . $arrPath[1];		
		} else {
			$new_path = IMAGE_UPLOAD_DIR.$image_thumb;
		}
		$thumb->save($new_path);
		return $new_path;		
	}	
	/**
	*	@author: Pham Van Diep
	*	@date: 12/2/2014
	*	@description: crop image tao avatar	
	*	@param: string duong dan cua hinh		
	*	@param: int chieu rong cua hinh duoc crop
	*	@param: int chieu cao cua hinh duoc crop
	*	@return: duong dan hinh sau khi duoc crop
	*/
	public static function crop($image_src, $width = IMAGE_AVATAR_WIDTH, $height = IMAGE_AVATAR_WIDTH,  $image_thumb=null) {
	
		include_once('Crop.php');
		$crop = new CI_Crop();		
		if(isset($image_thumb)) {
			$image_avatar = IMAGE_UPLOAD_DIR.$image_thumb;
		} else {
			$arrPath = explode('.',IMAGE_UPLOAD_DIR . $image_src);
			$image_avatar = $arrPath[0]. '.'. $width.'x'. $height. '.'.$arrPath[1];				
		}
		$crop->thumbSquare(IMAGE_UPLOAD_DIR . $image_src ,$image_avatar, $width, $height) ;
		return $image_avatar;		
	}
	
	/**
	*	@author: Pham Van Diep
	*	@date: 13/2/2014
	*	@description: generate image
	*	@param: string duong dan cua hinh		
	*	@param: int chieu rong cua hinh duoc crop
	*	@param: int chieu cao cua hinh duoc crop
	*	@return: duong dan hinh sau khi duoc crop hoac resize
	*/
	public static function generate($image_src, $width, $height) {		
		if((int)$width == (int)$height)
			return self::crop($image_src, $width, $height);
		return self::resize($image_src, $width, $height);
	}
    	
 }
 
